package com.xujicheng.dingtalk.oauth2;

import com.taobao.api.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 默认的获取access_token及续期策略
 * @author: xujicheng
 * @project dingtalk-utils
 * @packge com.xujicheng.dingtalk
 * @date: 2018/7/11 11:39
 * @description:
 */
@Slf4j
public class DefaultDingtalkOAuth2AccessToken implements DingtalkOAuth2AccessToken {

    private static String ACCESS_TOKEN ="";

    public DefaultDingtalkOAuth2AccessToken(DingtalkToken dingtalkToken){
        try {
            ACCESS_TOKEN = dingtalkToken.getToken();
            ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
            scheduledExecutorService.scheduleWithFixedDelay(new AccessTokenRenewalTask(dingtalkToken),60L,60L,TimeUnit.SECONDS);
        } catch (ApiException e) {
            log.error("获取AccessToken失败，响应的错误信息：{}",e.getMessage());
            throw new RuntimeException(e.getErrMsg());
        }

    }

    @Override
    public String getAccessToken() {
        return this.ACCESS_TOKEN;
    }
}
